﻿using LitJson;
using MobaCommon.Code;
using MobaCommon.Dto;
using MobaCommon.OpCode;
using MOBAServer.Cache;
using MOBAServer.Model;
using MOBAServer.Room;
using Photon.SocketServer;
using System;
using System.Collections.Generic;

namespace MOBAServer.Logic
{
    class PlayerHandler : SingeSend, IOpHandler
    {
        public Action<List<int>, List<int>> startSekectEvent;
        /// <summary>
        /// 账号缓存
        /// </summary>
        private AccountCache accountCache = Caches.Account;
        /// <summary>
        /// 玩家缓存
        /// </summary>
        private PlayerCache playerCache = Caches.Player;
        /// <summary>
        /// 匹配缓存
        /// </summary>
        private MatchCache matchCache = Caches.Match;
        public void OnDisconnect(MobaClient client)
        {
            //第15个视频 22分钟
            MobaClient temClient = null;
            foreach (var item in playerCache.GetFriends(client))
            {
                if (playerCache.HasOnline(item))
                {
                    temClient = playerCache.GetClient(item);
                    int playerId = playerCache.GetId(client);
                    Send(temClient, OpCode.PlayerCode, OpPlayer.FriendOffline, 0, "下线", playerId);
                }
            }
            matchCache.Offline(client,playerCache.GetId(client));
            playerCache.Offline(client);
        }

        public void OnRequest(MobaClient client, byte subCode, OperationRequest request)
        {
            switch (subCode)
            {
                case OpPlayer.GetInfo:
                    OnGetInfo(client);
                    break;
                case OpPlayer.Creat:
                    string name = request[0].ToString();
                    OnCreate(client, name);
                    break;
                case OpPlayer.Online:
                    Online(client);
                    break;
                case OpPlayer.Add:
                    string addName = request[0].ToString();
                    OnAdd(client, addName);
                    break;
                case OpPlayer.AddRequest:
                    OnAddRequest(client, (bool)request[0], (int)request[1]);
                    break;
                case OpPlayer.StartMatch:
                    OnStartMatch(client, (int)request[0]);
                    break;
                case OpPlayer.StopMatch:
                    OnStopMatch(client);
                    break;
                default:

                    break;
            }
        }

        private void OnStopMatch(MobaClient client)
        {
            bool result = matchCache.StopMatch(client, playerCache.GetId(client));
            if(result)
            {
                Send(client, OpCode.PlayerCode, OpPlayer.StopMatch, 0, "离开成功");
            }
        }

        private void OnStartMatch(MobaClient client, int playerId)
        {
            if (playerCache.GetId(client) != playerId)
                return;
            MatchRoom room = matchCache.StartMatch(client, playerId);
            Send(client, OpCode.PlayerCode, OpPlayer.StartMatch, 0, "开始匹配");
            if (room.IsFull)
            {
                //开始选人
                startSekectEvent(room.team1IdList,room.team2IdList);
                //发起是否进入选人请求
                room.Broast(OpCode.PlayerCode,OpPlayer.MatchComplete,0, "是否进入选人界面(10s内)");
                //摧毁房间
                matchCache.DestroyRoom(room);
            }
        }
        /// <summary>
        /// 添加结果
        /// </summary>
        private void OnAddRequest(MobaClient client, bool result, int requestId)
        {
            MobaClient requestClient = playerCache.GetClient(requestId);
            if (result)
            {
                int playerId = playerCache.GetId(client);
                playerCache.AddFriend(playerId, requestId);
                Send(client, OpCode.PlayerCode, OpPlayer.AddRequest, 1, "", JsonMapper.ToJson(ToDto(playerCache.GetModel(playerId))));
                Send(requestClient, OpCode.PlayerCode, OpPlayer.AddRequest, 1, "", JsonMapper.ToJson(ToDto(playerCache.GetModel(requestId))));
            }
            else
            {

                Send(requestClient, OpCode.PlayerCode, OpPlayer.AddRequest, -1, "拒绝好友请求");
            }
        }
        private void OnAdd(MobaClient client, string addName)
        {
            PlayerModel toPlayerModel = playerCache.GetModel(addName);
            if (toPlayerModel == null)
            {
                Send(client, OpCode.PlayerCode, OpPlayer.Add, -1, "没有此角色");
                return;
            }
            //如果添加的是自身那么不可以
            if (playerCache.GetModel(client).Id == toPlayerModel.Id)
            {
                Send(client, OpCode.PlayerCode, OpPlayer.Add, -3, "不能添加自身");
            }
            else
            {
                bool isOnline = playerCache.HasOnline(toPlayerModel.Id);
                if (!isOnline)
                {
                    Send(client, OpCode.PlayerCode, OpPlayer.Add, -2, "此玩家不在线");
                    return;
                }
                MobaClient toClient = playerCache.GetClient(toPlayerModel.Id);
                PlayerModel model = playerCache.GetModel(client);
                string playerDtoJson = JsonMapper.ToJson(ToDto(model));
                Send(toClient, OpCode.PlayerCode, OpPlayer.AddRequest, 0, "是否添加好友", playerDtoJson);
            }


        }
        /// <summary>
        /// 玩家上线
        /// </summary>
        /// <param name="client"></param>
        private void Online(MobaClient client)
        {
            int accId = accountCache.GetId(client);
            int playerId = playerCache.GetId(accId);
            if (playerCache.HasOnline(client))
                return;

            playerCache.Online(client, playerId);

            #region 上线通知好友更改状态
            MobaClient temClient = null;
            foreach (var item in playerCache.GetFriends(client))
            {
                if (playerCache.HasOnline(item))
                {
                    temClient = playerCache.GetClient(item);
                    Send(temClient, OpCode.PlayerCode, OpPlayer.FriendOnline, 0, "上线", playerCache.GetId(client));
                }
            }
            #endregion


            string playerJson = JsonMapper.ToJson(ToDto(playerCache.GetModel(playerId)));
            Send(client, OpCode.PlayerCode, OpPlayer.Online, 0, "上线成功", playerJson);
        }
        private PlayerDto ToDto(PlayerModel model)
        {
            PlayerDto playerDto = new PlayerDto()
            {
                id = model.Id,
                exp = model.Exp,
                loseCount = model.LoseCount,
                name = model.Name,
                level = model.Level,
                power = model.Power,
                runCount = model.RunCount,
                winCount = model.WinCount,
                heroIds = new int[model.HeroIdList.Count],
                friends = new Friend[model.FriendIdList.Count]
            };
            for (int i = 0; i < model.HeroIdList.Count; i++)
            {
                playerDto.heroIds[i] = model.HeroIdList[i];
            }
            Friend[] friends = new Friend[model.FriendIdList.Count];
            for (int i = 0; i < model.FriendIdList.Count; i++)
            {
                int id = model.FriendIdList[i];
                PlayerModel playerModel = playerCache.GetModel(id);
                friends[i] = new Friend(id, playerModel.Name, playerCache.HasOnline(id));
            }
            playerDto.friends = friends;
            return playerDto;

        }
        /// <summary>
        /// 创建角色
        /// </summary>
        /// <param name="client"></param>
        /// <param name="name"></param>
        private void OnCreate(MobaClient client, string name)
        {
            int accId = accountCache.GetId(client);
            if (playerCache.Has(accId))
                return;
            playerCache.Create(name, accId);
            Send(client, OpCode.PlayerCode, OpPlayer.Creat, 0, "创建成功");
        }
        /// <summary>
        /// 获取角色信息
        /// </summary>
        private void OnGetInfo(MobaClient client)
        {
            int accId = accountCache.GetId(client);
            if (accId == -1)
            {
                Send(client, OpCode.PlayerCode, OpPlayer.GetInfo, -1, "非法登录");
                return;
            }
            if (playerCache.Has(accId))
            {
                int playerId = playerCache.GetId(accId);
                PlayerModel model = playerCache.GetModel(playerId);
                string playerJson = JsonMapper.ToJson(ToDto(model));
                Send(client, OpCode.PlayerCode, OpPlayer.GetInfo, 0, "存在角色", playerJson);
            }
            else
            {
                Send(client, OpCode.PlayerCode, OpPlayer.GetInfo, -2, "不存在角色");
            }
        }
    }
}
